<template>
  <div>
    <el-upload
      :limit="1"
      action="#"
      list-type="picture"
      :auto-upload="false"
      accept="image/png,image/gif,image/jpg,image/jpeg"
      :on-success="handleSuccess"
      :on-change="imgSaveToUrl"
      :show-file-list="false"
      ref="frontUpload"
    >
      <el-avatar :size="50" :src="imageFrontUrl" />
    </el-upload>
  </div>
</template>
<script setup>
import { ref, defineProps, onMounted, defineEmits } from 'vue'
import { ElMessage } from 'element-plus'
const emit = defineEmits(['toFather'])
const props = defineProps(['imageUrl'])
const imageFrontUrl = ref('')
onMounted(() => {
  imageFrontUrl.value = props.imageUrl
})
function imgSaveToUrl(file) {
  imageFrontUrl.value = URL.createObjectURL(file.raw)
  const fileSize = file.size
  const fileType = file.raw.type
  if (!fileSize) {
    // 是否为空
    ElMessage({
      type: 'error',
      showClose: true,
      message: '无效的文件，请重新选择！'
    })
    logoPicRemove()
    return
  }
  if (fileSize / 1024 / 1024 > 10) {
    // 图片大小
    ElMessage({
      type: 'error',
      showClose: true,
      message: '请上传小于10M的图片！'
    })
    logoPicRemove()
    return
  }
  if (fileType.indexOf('image') === -1) {
    // 如果不是图片格式
    ElMessage({
      type: 'error',
      showClose: true,
      message: '不是有效的图片文件，或格式不支持，请重新选择!'
    })
    logoPicRemove()
    return
  }
  emit('toFather', imageFrontUrl.value)
}
function logoPicRemove() {
  imageFrontUrl.value = ''
}
</script>
